package com.ac.scum.log.task.service;

import com.ac.scum.log.bean.Package;
import com.ac.scum.log.bean.Server;
import com.ac.scum.log.task.mapper.pack.PackageMapper;
import com.ac.scum.log.task.mapper.server.ServerMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@AllArgsConstructor
public class ServerService {
    private final ServerMapper serverMapper;
    private final PackageMapper packageMapper;

    public List<Server> getServersWithSpecifiedPackageIds(Long... packageIds) {
        if (packageIds == null || packageIds.length == 0) {
            return new ArrayList<>();
        }
        StringBuilder innerSql = new StringBuilder();
        Arrays.stream(packageIds).forEach(item -> innerSql.append(item).append(","));
        List<Package> packagesBySpecifiedPackageIds = packageMapper.getPackagesBySpecifiedPackageIds(innerSql.substring(0,innerSql.length()-1));
        if (packagesBySpecifiedPackageIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<Long> serverIds = packagesBySpecifiedPackageIds.stream().map(Package::getServerId).toList();
        List<Server> servers = serverMapper.selectBatchIds(serverIds);

        servers.forEach(server -> server.setPackages(packagesBySpecifiedPackageIds.stream().filter(item -> item.getServerId().equals(server.getId())).toList()));
        return servers;
    }
}
